import axios from 'axios'
import { isDev } from './config'
/*
* 全局 axios 默认配置
*/
// axios.defaults.baseURL = isDev ? 'http://localhost:3000' : '/'
axios.defaults.timeout = 50000
axios.defaults.headers.common.systoken = ''
axios.defaults.headers.get['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers.get.Accept = 'application/json'
axios.defaults.headers.post['Content-Type'] = 'application/json'

function transformRequest(param) {
  return Object.keys(param).map(key => {
    const value = typeof param[key] === 'object' ? encodeURIComponent(JSON.stringify(param[key])) : param[key]
    return `${key}=${value}`
  }).join('&')
}

function request(options) {
  return new Promise((resolve, reject) => {
    axios(options).then(res => {
      resolve(res.data)
    }, err => {
      handleError(err)
      reject(err)
    })
  })
}

function handleError(error) {
  console.log(error)
}

export default {
  get(url, params = {}) {
    return request({
      url: url,
      method: 'get',
      params: params,
      paramsSerializer: function (params) {
        return transformRequest(params)
      }
    })
  },

  post(url, data = {}) {
    return request({
      url: url,
      method: 'post',
      data: data,
      transformRequest: [function (data, headers) {
        return JSON.stringify(data)
      }]
    })
  },

  delete(url, params) {
    return request({
      url: url,
      method: 'delete',
      params: params,
      paramsSerializer: function (params) {
        return transformRequest(params)
      }
    })
  },
  head(url, params) { },
  options(url, params) { },
  put(url, params) { },
  patch(url, params) { }
}
